<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="confirmLoading">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :label="$t('reportQuery.customer')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select :placeholder="$t('reportQuery.customer')" showSearch
                    :dropdownMatchSelectWidth="false" v-decorator="[ 'organId', validatorRules.organId ]" optionFilterProp="children">
                    <a-select-option v-for="(item,index) in supList" :key="index" :value="item.id">
                      {{ item.supplier }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
          </a-col>
          <!-- 关联订单 -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.relatedOrder')" data-step="3"
              :data-title="$t('popup.relatedOrder')" :data-intro="$t('popup.purchaseReceiptAfterOrder')">
              <a-input-search :placeholder="$t('popup.pleaseSelectAssociated')" v-decorator="['number',validatorRules.number]"
                @search="onSearchLinkNumber" :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('defaultTranslate.operator')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator="[ 'userName']" :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['billTime', validatorRules.billTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="['billNo',validatorRules.billNo]" disabled
                :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table
          :ref="refKeys[0]"
          :loading="accountTable.loading"
          :columns="accountTable.columns"
          :dataSource="accountTable.dataSource"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="true"
          :actionButton="true"
          @inputPurchaseValueChange="onChange"
          @valueChange="onValueChange">
          <template #delete="record">
            <div style="text-align: center;">
              <a-popconfirm :title="$t('manuManagement.areDelete')"
                @confirm="() => removeRows(record)">
                <a-icon type="delete"></a-icon>
              </a-popconfirm>
            </div>
          </template>
          <template #rowIndex="record">
            <div style="text-align: center;">{{ record.index + 1 }}</div>
          </template>
        </j-editable-table>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="24" :md="24" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="{xs: { span: 24 },sm: { span: 24 }}" label="">
              <a-textarea :rows="2" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="[ 'remark' ]" style="margin-top:8px;"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.amountCollected')">
              <a-input :placeholder="$t('popup.pleaseCollectionAmount')" v-decorator.trim="[ 'totalPrice' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.amountCollected')">
              <a-input :placeholder="$t('popup.pleaseCollectionAmount')" v-decorator.trim="[ 'custom9',validatorRules.custom9 ]" @input="amountChange"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.giveChange')">
              <a-input style="width:185px;" :placeholder="$t('popup.giveChange')" v-decorator.trim="[ 'custom8' ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" style="visibility: hidden">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('financialManagement.totalAmount')">
              <a-input :placeholder="$t('popup.pleaseTotalCollection')" v-decorator.trim="[ 'changeAmount' ]" :readOnly="true" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.enclosure')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="financial"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <person-modal ref="personModalForm" @ok="personModalFormOk"></person-modal>
    <link-bill-list ref="linkBillList" @ok="linkBillListOk"></link-bill-list>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import { findBySelectCus, findBySelectSup } from '@/api/api'
  import PersonModal from '@/views/system/modules/PersonModal'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { FinancialModalMixin } from '../mixins/FinancialModalMixin'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import LinkBillList from '@/views/bill/dialog/LinkBillList'
  export default {
    name: "AdvanceReceivedModel",
    mixins: [JEditableTableMixin, FinancialModalMixin],
    components: {
      PersonModal,
      JUpload,
      JDate,
      LinkBillList,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title:this.$t('setailManagement.operation'),
        width: '1600px',
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        model: {},
        fileList:[],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['accountDataTable', ],
        activeKey: 'accountDataTable',
        accountTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('commodityManagement.delete'), width: '3%', key: 'delete', type: 'slot' },
            { title: this.$t('defaultTranslate.lineNumber'), key: 'rowIndex', width: '4%', type: 'slot' },
            { title: this.$t('popup.titleOfAccount'),key: 'accountId',width: '20%', type: FormTypes.select, placeholder: this.$t('inPrint.pleaseTnter')+'${title}', options: [],
              allowSearch:true, validateRules: [{ required: true, message:'${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('manuManagement.amountReceived'),key: 'needDebt', width: '10%', type: FormTypes.inputNumber, statistics: true, placeholder: this.$t('inPrint.pleaseTnter')+'${title}',disabled:true,
              validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('financialManagement.receivedAmount'), key: 'straightDeposit', width: '10%',readonly: true, type: FormTypes.inputNumber, placeholder: this.$t('inPrint.pleaseTnter') + '${title}',disabled:true, },
            { title: this.$t('reportQuery.amount'),key: 'eachAmount', width: '10%', type: FormTypes.inputNumber, statistics: true, placeholder: this.$t('inPrint.pleaseTnter')+'${title}',
              validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') },{handler:this.validateCheckNumber, message: '${title}' }]
            },
            { title: this.$t('financialManagement.checkNumber'),key: 'invoiceNo', width: '12%', type: FormTypes.hidden, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'},
            { title: this.$t('reportQuery.remarks'),key: 'remark', width: '30%', type: FormTypes.input, placeholder: this.$t('inPrint.pleaseTnter')+'${title}'}
          ]
        },
        confirmLoading: false,
        validatorRules:{
          organId:{
            rules: [
              { required: true, message: this.$t('popup.pleasePaymentMember')+'!' }
            ]
          },
          handsPersonId:{
            rules: [
              { required: true, message:this.$t('popup.pleaseSelectPersonnel')+'!'}
            ]
          },
          billTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectDocumentDate')+'!' }
            ]
          },
          billNo:{
            rules: [
              { required: true, message: this.$t('otherJS.DocumentNoFailure') }
            ]
          },
        custom9: {
          rules: [
            { required: true, message: this.$t('popup.pleasePaymentAmount') + '!' },
            {required: true,validator:this.checkChangeAmount}
          ]
        },
          number:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectAssociated') }
            ]
          }
        },
        prefixNo: 'ZFYS',
        url: {
          add: '/accountHead/addAccountHeadAndDetail',
          edit: '/accountHead/updateAccountHeadAndDetail',
          detailList: '/accountItem/getDetailList'
        }
      }
    },
    created () {
    },
    methods: {
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        this.initSupplier()
        this.billStatus = '0'
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.fileList = []
          this.$nextTick(() => {
            this.form.setFieldsValue({custom8:0})
          });
        } else {
          this.model.billTime = this.model.billTimeStr
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'handsPersonId', 'billTime', 'billNo', 'remark','number','userName','creator',
            'custom9','custom8',
                  'totalPrice', 'changeAmount'))
          });
          
          // 加载子表数据
          let params = {
            headerId: this.model.id
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.accountTable);
        }
        this.initRetail()
        this.initPerson()
        this.initDetailAccount()
      },
      initSupplier() {
        let that = this;
        findBySelectCus({}).then((res)=>{
          if(res) {
            that.supList = res;
          }
        });
      },
      onSearchLinkNumber() {
        let organId = this.form.getFieldValue('organId')
        // this.$refs.linkBillList.show('其它', this.$t('manuManagement.purchaseOrder'), this.$t('warehouseManagement.supplier'), "1,3", organId)
        this.$refs.linkBillList.acceptanceShow('其它', '厂家直发', this.$t('manuManagement.customer'), "1,2,3", organId, this.prefixNo)
        this.$refs.linkBillList.title = this.$t('manuManagement.directOrdersFromManufacturers')
      },
    linkBillListOk(selectBillDetailRows) {
      this.rowCanEdit = false
      if(selectBillDetailRows && selectBillDetailRows.length>0) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            'number': selectBillDetailRows[0].number
          })
        })
        this.accountTable.dataSource = selectBillDetailRows;
        let totalPrice = 0
        selectBillDetailRows.forEach(item => {
          item.eachAmount = this.$toDecimal(item.totalPrice - (item.straightDeposit || 0))
          item.needDebt = item.totalPrice
          totalPrice = this.__addition(Number(item.totalPrice - item.straightDeposit), totalPrice)
        })
        this.totalPrice = totalPrice
        this.$nextTick(() => {
            setTimeout(()=>{
              this.form.setFieldsValue({
              totalPrice: totalPrice,
              changeAmount: totalPrice,
              organId: selectBillDetailRows[0].organId,
              custom8:0,
              custom9:totalPrice
            })
          },200);
        })
      }
    },
    
    // 校验jedittable 数字大于0
    validateCheckNumber(type, value, row, column, callback, target) {
      let allValues = target.inputValues
      let currentRow = allValues.find(v=>v.id.includes(row.id))
      if(+value < 0 ){
        callback(false,this.$t('otherJS.greaterThan0'))
        return
      }else if(currentRow && currentRow.needDebt && +value > currentRow.needDebt){
        callback(false,this.$t('financialManagement.cannotMoreThanOrder'))
      } else{
        callback(true)
      } 
    },
    
    checkChangeAmount(rule, value, callback){
      const table = this.$refs[this.refKeys[0]]
      table.getValues((err,v)=>{
        let totalPrice = v.reduce((total,item)=>{
          return total + (+item.eachAmount)
        },0)
        if(+value < totalPrice){
          callback(this.$t('financialManagement.cannotLessThanReceived'));
        }
        callback()
      })
    },
    onChange ({row,column,value, target}) {
      target.getValues((err, values) => {
        const total = values.reduce((pre, cur) => {
          return this.__addition(pre, Number(cur.eachAmount))
        }, 0)
        let custom8 = this.$toDecimal(total - this.totalPrice)
        custom8 = custom8 > 0 ? custom8 : 0
        this.form.setFieldsValue({
          changeAmount: custom8 > 0 ? this.totalPrice : total,
          totalPrice: custom8 > 0 ? this.totalPrice : total,
          custom8: custom8,
          custom9: total,
        })
      }, true)
      if(column.key === 'accountId'){
        let item = column.options.find(v=>v.value === value)
        if(item && item.type === '1'){
          this.changeFormTypesToInput(this.accountTable.columns, 'invoiceNo', 1)
        }else{
          this.changeFormTypesToInput(this.accountTable.columns, 'invoiceNo', 0)
        }
      }
    },
    
    
    amountChange(e){
      this.form.validateFields(['changeAmount'])
      // 定金
      let discountMoney  = this.form.getFieldValue('discountMoney') 
      let totalPrice = this.form.getFieldValue('totalPrice') 
          let custom10 = this.form.getFieldValue('custom10') 
          custom10 = custom10 || 0
          let changeAmount = this.__substraction(totalPrice, this.discountMoney)
          // 实际应付款
          let num = changeAmount - custom10 > 0 ? ((changeAmount*100 - custom10*100)/100).toFixed(2) : 0
          // 当前付款
          let currentAmount = e.target.value
          let custom8 = +currentAmount - totalPrice < 0 || isNaN(+currentAmount - totalPrice) ? 0 :(( +currentAmount*100 - totalPrice*100)/100).toFixed(2)
          this.form.setFieldsValue({
            custom8: custom8,
            changeAmount: currentAmount >= totalPrice ? totalPrice :  currentAmount,
            // custom9:currentAmount >= totalPrice ? totalPrice :  currentAmount
          })
    },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values;
        billMain.type = '直发预收款'
        if(this.fileList && this.fileList.length > 0) {
          billMain.fileName = this.fileList
        }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.status = this.billStatus
        billMain.creator = this.$attrs.userList.find(item => item.userName === billMain.userName).id
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      removeRows (text) {
        this.$refs[this.refKeys[0]].removeRows(text.rowId)
      }
    }
  }
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>